package main

import (
	"context"
	"fgo/advance/grpc/grpc-gateway/hello-http-ca-tls/tools"
	pb "fgo/advance/grpc/grpc-gateway/proto/hello"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
	"net"
)

const (
	// Address gRPC服务地址
	Address = "127.0.0.1:50052"
)

// 定义helloService并实现约定的接口
type helloService struct{}

// HelloService ...
var HelloService = helloService{}

func (h helloService) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	resp := new(pb.HelloReply)
	resp.Message = "Hello " + in.Name + "."

	return resp, nil
}

//x509.NewCertPool()：创建一个新的、空的 CertPool
//certPool.AppendCertsFromPEM()：尝试解析所传入的 PEM 编码的证书。如果解析成功会将其加到 CertPool 中，便于后面的使用
//credentials.NewTLS：构建基于 TLS 的 TransportCredentials 选项
//tls.Config：Config 结构用于配置 TLS 客户端或服务器
func main() {

	// TLS认证
	tlsServer := tools.Server{
		CaFile:   "../../keys-ca/ca.pem",
		CertFile: "../../keys-ca/server.pem",
		KeyFile:  "../../keys-ca/server.key",
	}

	creds, err := tlsServer.GetCredentialsByCA()
	if err != nil {
		grpclog.Fatalf("GetTLSCredentialsByCA err: %v", err)
	}

	// 实例化grpc Server, 并开启TLS认证
	s := grpc.NewServer(grpc.Creds(creds))

	// 注册HelloService
	pb.RegisterHelloServer(s, HelloService)

	grpclog.Info("Listen on " + Address + " with TLS")

	listen, err := net.Listen("tcp", Address)
	if err != nil {
		grpclog.Fatalf("failed to listen: %v", err)
	}

	s.Serve(listen)
}
